<template>
  <div class="InitiateContent">
    <a-form-model layout="inline" :model="form" ref="ruleForm">
      <a-comment>
        <a-avatar slot="avatar" v-if="type == 4" :src="avatarUrl2" alt="AI" />
        <a-avatar slot="avatar" v-else :src="avatarUrl1" alt="AI" />
        <div slot="content" class="itemContent box_shadow">
          
          <div class="describe">{{ describe }}
          </div>

          <div class="operation" v-if="type != '3' && type != '4' && formList.length">
            <a-form-model-item v-for="(jtem, jKey) in formList" :key="jKey" :label="jtem.name" :prop="jtem.key"
              :rules="{ required: true, message: ' ', trigger: 'blur', }">
              <a-input size="small" v-if="!jtem.optionsList" v-model="form[jtem.key]" />
              <a-select size="small" show-search option-filter-prop="children" v-else v-model="form[jtem.key]"
                :filter-option="filterOption">
                <a-select-option v-for="(item, key) in jtem.optionsList" :key="key" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </div>


          <div class="btn">
            <div class="inputBtn" v-if="type == '1'">
              <span>课文/知识点</span>
              <a-form-model-item class="center" prop="userName"
                :rules="{ required: true, message: ' ', trigger: 'blur', }">
                <a-input size="small" style="width: 100%;" v-model="form['userName']">
                </a-input>
              </a-form-model-item>
              <a-form-model-item class="right">
                <a-button 
                  size="small" 
                  type="danger" 
                  :loading="btnLoading"
                   v-if="step == 1"
                   @click="handleSubmit">下一步</a-button>
              </a-form-model-item>
            </div>

            <div class="inputBtn" v-if="type == '2'">
              <div></div>
              <a-form-model-item>
                <a-button size="small" type="danger" :loading="btnLoading" @click="createContent">
                  生成教学内容和学情分析
                </a-button>
              </a-form-model-item>
            </div>
          </div>
        </div>
      </a-comment>
    </a-form-model>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapState } from "vuex";
let { mapMutations, mapActions } = createNamespacedHelpers("adminBasic");

export default {
  name: 'initiateContent',
  props: {
    formList: Array,
    describe: String,
    type: String
  },
  computed: {
    sessionId() {
      return this.$store.state.sessionId
    },
    btnLoading() {
      return this.$store.state.btnLoading
    }
  },
  data() {
    return {
      step: 1,
      avatarUrl1: require('@/assets/img/ai.png'),
      avatarUrl2: require('@/assets/img/Avatar.png'),
      form: {
        '学生水平差异': "较大",
        '对学习内容态度': "态度被动消极",
        '课文': "第一篇",
        '年级': "一年级",
        'userName': "狼牙山五壮士",
        'userName': "狼牙山五壮士",
        '本节课掌握程度': "从未学过",
        '学习动机': "较强",
        '学生人数': "2",
        '学段': "小学",
        '先验知识掌握水平': "较差",
        '课时': "1",
        '学科': "语文",
        '教材': "人教版",
        '总课时': "1",
        '单元': "第一单元",
      },
    }
  },
  watch: {
    // formList: {
    //     handler(newVal) {
    //         let obj = {}
    //         newVal.forEach(item => {
    //             obj[item.value] = item.name;
    //         });
    //         this.form = obj;
    //     },
    //     deep: true,
    //     immediate: true
    // },
  },

  created() {


    // const source = new this.$EventSourcePolyfill("/api/v1/chains/chat-stream?session_id=7217a240-9d72-4937-a89f-ad5846143aee&step_name=xqfx&force=true", { 
    //   withCredentials: true,
    //   headers: {
    //     'Access-Control-Allow-Origin': '*',
    //     Authorization: localStorage.getItem('Authorization')
    //   }
    // });

    // console.log(source)
  },


  methods: {
    ...mapActions([
      'formGet',
      'post'
    ]),

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },

    handleSubmit(e) {
      this.$refs["ruleForm"].validate(valid => {
        console.log(valid, "?_?")
        if (valid) {
          this.$store.commit('setBtnLoading', true)
          setTimeout(() => {
            this.$emit('getForm1', this.form)
            this.step = 2;
          }, 1500)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    createContent() {
      this.form = Object.assign(this.form, this.$parent.form1)
      this.$store.commit(`setForm`, this.form);
      console.log(this.form)

      this.$store.commit(`setG_loading`, true);

      let data = {
        "phase": this.form['学段'],
        "subject": this.form['学科'],
        "grade": this.form['年级'],
        "textbook": this.form['教材'],
        "unit": this.form['单元'],
        "chapter": this.form['课文'],
        "lesson": this.form['userName'],
        "total_section": this.form['总课时'],
        "section": this.form['课时'],
        "knowledge": this.form['userName'],
        "num_of_students": this.form['学生人数'],
        "master_degree": this.form['本节课掌握程度'],
        "prior_knowledge": this.form['先验知识掌握水平'],
        "academic_level": this.form['学生水平差异'],
        "attitude": this.form['对学习内容态度'],
        "motivation": this.form['学习动机'],
      }

      // this.$axios.post('/api/v1/chat_sessions/', data).then(res => {
      //   console.log(res);
      // }).catch(err => {
      //   this.$message.error(err);
      // })

      this.post({
        API: 'createSession',
        data: data
      }).then(res => {
        console.log(res,"??");
        this.$store.commit(`setSessionId`, res.session_id);

        this.chat('jxnr', res.session_id)
        this.chat('xqfx', res.session_id)
        // this.chat('jxmb')
        // this.chat('jxpj')
        // this.chat('jxgc')

        // this.chat('jcjj')

      }).catch(err => {
        this.$message.error(err);
      })
    },

    chat(type, sessionId) {
      // console.log(type, "type")
      this.$store.commit(`setG_loading`, true);

      let str = ''

      const source = new this.$EventSourcePolyfill(`/api/v1/chains/chat-stream?session_id=${sessionId}&step_name=${type}&force=true`, { 
        withCredentials: true,
        headers: {
          'Access-Control-Allow-Origin': '*',
          Authorization: localStorage.getItem('Authorization')
        }
      });
      source.onopen = function() {
        console.log("Connection to server opened.");
      };
      source.onerror = function(event) {
        source.close();
        console.log("Error", event);
      };
      source.addEventListener('message', (event) => {
        this.$store.commit(`setG_loading`, false);

        if (event.data === "CLOSED") {
          console.log("Connection to server closed.");
          source.close();

          
          this.$emit('step2Compelete', true)

          return;
        }
        str += event.data;

        this.$store.commit(`set${type}`, str);
        // console.log("printing event data: " + JSON.stringify(event))
      })


      return false    // 老功能
      this.$axios.post(`/api/v1/chains/chat?session_id=${sessionId}&step_name=${type}&force=true`, {})
        .then(res => {
          if (res.status == 200) {
            let data = res.data
            this.$store.commit(`set${type}`, data);
            this.$store.commit(`setG_loading`, false);
            // this.$store.commit('setContent', data);
          }
        }).catch(err => {
          this.$message.error(err);
        })

    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.InitiateContent {
  .itemContent {
    margin-right: 5px;
    position: relative;
    background-color: #fff;
    border-radius: 8px;
    /* 创建左上角圆角 */
    padding: 10px;
    // box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.2);
  }

  .itemContent::before {
    // content: "";
    // position: absolute;
    // z-index: 10;
    // width: 0;
    // height: 0;
    // left: -10px;
    // top: 3.8px;
    // /* 调整尖角的高度 */
    // border-bottom: 10px solid transparent;
    // border-top: 10px solid transparent;
    // border-right: 10px solid #f2f2f2;
    // /* 创建尖角 */
  }

  .btn {
    .inputBtn {
      display: flex;

      justify-content: space-between;

      >span {
        line-height: 40px;
        margin-right: 10px;
        flex: 116px;
      }

      .center {
        width: 100%;
      }

      .right {
        margin-right: 0;
      }
    }
  }
}
</style>